/*
* Copyright (C) Microsoft. All rights reserved.  
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not 
* use this file except in compliance with the License.  You may obtain a copy 
* of the License at http://www.apache.org/licenses/LICENSE-2.0  
* 
* THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED 
* WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, 
* MERCHANTABLITY OR NON-INFRINGEMENT. 
*
* See the Apache License, Version 2.0 for specific language governing 
* permissions and limitations under the License.
*
*/
#pragma once

#include <string>
#include <vector>
#include <memory>
#include <baja/db/db.h>
#include <journal/models/db/table_interfaces.h>

namespace journal { namespace model { namespace db
{

class notebook_table :
    public inotebook_table,
    public icommon_table_client
{
public:
    notebook_table();
    static std::shared_ptr<inotebook_table> create(std::shared_ptr<s::iengine> dbEngine);

    // icommon_table_client
    void defineColumns(std::shared_ptr<s::itable> table);
    void defineIndexColumns(std::shared_ptr<s::iindex> primaryKeyIndex);
    void defineRowCells(std::shared_ptr<std::vector<std::shared_ptr<s::icell>>> row);

    // ibase_table
    std::shared_ptr<icommon_table> common();

    // inotebook_table
    void write(const std::vector<size_t>& v);
    void read(std::vector<size_t>& v);

private:
    std::recursive_mutex _mutex;

    static const b::uint32 singletonId;

    std::shared_ptr<icommon_table> _commonTable;
    std::weak_ptr<icommon_table_client> _commonTableClient;

    std::shared_ptr<s::icolumn_typed<b::uint32>> _notebookIdColumn;
    std::shared_ptr<s::icolumn_typed<b::uint32>> _notebookBlobSizeColumn;
    std::shared_ptr<s::icolumn_typed<s::binary_blob>> _notebookBlobColumn;

    std::shared_ptr<s::icell_typed<b::uint32>> _notebookIdCell;
    std::shared_ptr<s::icell_typed<b::uint32>> _notebookBlobSizeCell;
    std::shared_ptr<s::icell_typed<s::binary_blob>> _notebookBlobCell;

    std::shared_ptr<s::iindex_column> _notebookIdIndexColumn;

    std::shared_ptr<std::vector<std::shared_ptr<s::icell>>> _blobCells;

    std::shared_ptr<std::vector<std::shared_ptr<s::iresult_row>>> findRow(const b::uint32& id);

    // helpers
    void write(
        const b::uint32& id,
        s::binary_blob& inBlob);

    void read(
        const b::uint32& id,
        s::binary_blob& outBlob);
};

std::shared_ptr<inotebook_table> createNotebookTable(std::shared_ptr<s::iengine> dbEngine);

}}} // namespace journal::model::db